<template>
  <div class="formula-content editor-content-view" ref="container" v-html="processedHtmlWithImages"></div>
</template>

<script>
import {renderFormulasInElement, renderFormulasInHtml} from '@/utils/formula/formulaUtils'
import {getTempToken} from "@/api/files/file";
import {Message} from "element-ui";

export default {
  name: 'FormulaRenderer',
  props: {
    html: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      processedHtmlWithImages: '',
      imageTokens: {}
    }
  },
  computed: {
    processedHtml() {
      return renderFormulasInHtml(this.html)
    }
  },
  watch: {
    html: {
      immediate: true,
      async handler(newVal) {
        await this.processHtmlWithImages(newVal)
        this.$nextTick(() => {
          this.renderFormulas()
        })
      }
    }
  },
  mounted() {
    this.renderFormulas()
  },
  methods: {
    async processHtmlWithImages(html) {
      try {
        // 1. 得到所有图片的alt属性值
        const imgAlts = this.extractImgAlts(html)

        if (imgAlts.length > 0) {
          // 2.  获取临时token和文件信息
          const res = await getTempToken(imgAlts.join(','))
          if (res.code !== 200) {
            throw new Error('Failed to get temporary tokens: ' + (res.msg || ''))
          }

          // 3. 将文件信息映射到文件ID
          const fileInfoMap = {}
          res.data.forEach(fileInfo => {
            fileInfoMap[fileInfo.fileId] = fileInfo.fileUrl
          })

          // 4. 替换图片的src属性
          this.processedHtmlWithImages = this.replaceImgUrls(html, fileInfoMap)
        } else {
          this.processedHtmlWithImages = html
        }
      } catch (error) {
        console.error('Error processing images:', error)
        this.processedHtmlWithImages = html
      }
    },

    extractImgAlts(html) {
      if (!html) return []
      const parser = new DOMParser()
      const doc = parser.parseFromString(html, 'text/html')
      const imgs = doc.querySelectorAll('img')
      return Array.from(imgs).map(img => img.getAttribute('alt') || '')
    },

    replaceImgUrls(html, fileInfoMap) {
      if (!html) return html
      const parser = new DOMParser()
      const doc = parser.parseFromString(html, 'text/html')
      const imgs = doc.querySelectorAll('img')

      imgs.forEach(img => {
        const alt = img.getAttribute('alt') || ''
        const fileUrl = fileInfoMap[alt]
        if (fileUrl) {
          img.setAttribute('src', fileUrl)
        }
      })

      const serializer = new XMLSerializer()
      let updatedHtml = serializer.serializeToString(doc.body)
      updatedHtml = updatedHtml.replace(/^<body>|<\/body>$/g, '')

      return updatedHtml
    },

    renderFormulas() {
      if (this.$refs.container) {
        renderFormulasInElement(this.$refs.container)
      }
    }
  }
}
</script>

<style scoped>
.formula-content.editor-content-view {
  border: none !important;
  outline: none !important;
  box-shadow: none !important;
  background: none !important;
  padding: 0 !important;
  margin: 0 !important;
}

.formula-content >>> .katex {
  font-size: 1.1em;
  display: inline;
}

.formula-content >>> .katex-display {
  display: inline !important;
  margin: 0 !important;
  padding: 0 !important;
  text-align: inherit !important;
}

/* Ensure images are properly displayed */
.formula-content >>> img {
  max-width: 100%;
  height: auto;
}
</style>
